<template>
  <div class="sku-container">
    <a-card>
      <template #title>
        <a-space>
          <a-button @click="router.back()">
            <template #icon><left-outlined /></template>
            返回
          </a-button>
          <span>{{ productInfo.name }} - 规格管理</span>
        </a-space>
      </template>

      <!-- 操作按钮 -->
      <div style="margin-bottom: 16px">
        <a-button v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER" type="primary" @click="handleAdd">新增规格</a-button>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="skuList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total: number) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <img :src="record.image" alt="规格图片" style="width: 50px; height: 50px" />
          </template>
          <template v-if="column.key === 'price'">
            ¥{{ record.price }}
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === PRODUCT_STATUS.ACTIVE ? 'success' : 'default'">
              {{ PRODUCT_STATUS_TEXT[record.status] }}
            </a-tag>
          </template>
          <template v-if="column.key === 'auditStatus'">
            <a-tag :color="getAuditStatusColor(record.auditStatus)">
              {{ getAuditStatusText(record.auditStatus) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <!-- 农户可以编辑、上架下架、删除 -->
              <template v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER">
                <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                <a-button
                  type="link"
                  @click="handleToggleStatus(record)"
                >
                  {{ record.status === PRODUCT_STATUS.ACTIVE ? '下架' : '上架' }}
                </a-button>
                <a-popconfirm
                  title="确定要删除这个规格吗？"
                  @confirm="handleDelete(record)"
                >
                  <a-button type="link" danger>删除</a-button>
                </a-popconfirm>
              </template>
              <!-- 管理员只能审核和查看 -->
              <template v-else-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
                <a-button
                  v-if="record.auditStatus === AUDIT_STATUS.PENDING"
                  type="link"
                  @click="handleAudit(record)"
                >
                  审核
                </a-button>
              </template>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑规格弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
    >
      <a-form
        :model="skuForm"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="规格名称" name="quantity">
          <a-input v-model:value="skuForm.quantity" placeholder="如：大份、中份、小份" />
        </a-form-item>
        <a-form-item label="规格图片" name="image">
          <upload-image
            v-model:value="skuForm.image"
            :biz="BIZ_TYPE.PRODUCT_SPEC_IMG"
          />
        </a-form-item>
        <a-form-item label="价格" name="price">
          <a-input-number
            v-model:value="skuForm.price"
            :min="0"
            :precision="2"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="库存" name="stock">
          <a-input-number
            v-model:value="skuForm.stock"
            :min="0"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="skuForm.description"
            :rows="4"
            placeholder="请输入规格描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 审核弹窗 -->
    <a-modal
      v-model:visible="auditModalVisible"
      title="审核商品规格"
      @ok="handleAuditSubmit"
    >
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="规格名称">
          {{ currentSku?.quantity }}
        </a-form-item>
        <a-form-item label="价格">
          ¥{{ currentSku?.price }}
        </a-form-item>
        <a-form-item label="审核结果" name="auditStatus">
          <a-radio-group v-model:value="auditForm.auditStatus">
            <a-radio :value="AUDIT_STATUS.APPROVED">通过</a-radio>
            <a-radio :value="AUDIT_STATUS.REJECTED">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import {
  listProductSkuvoByPageUsingPost,
  addProductSkuUsingPost,
  updateProductSkuUsingPost,
  deleteProductSkuUsingPost
} from '@/api/productSkuController'
import { getProductVoByIdUsingGet } from '@/api/productController'
import UploadImage from '@/components/UploadImage.vue'
import { BIZ_TYPE } from '@/constants/upload'
import { formatDateTime } from '@/utils/format'
import { PRODUCT_STATUS, PRODUCT_STATUS_TEXT } from '@/constants/product'
import { PRODUCT_STATUS as AUDIT_STATUS, PRODUCT_STATUS_TEXT as AUDIT_STATUS_TEXT } from '@/constants/audit'
import { USER_ROLE } from '@/constants/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const productId = route.params.id as string
const userStore = useUserStore()

// 商品信息
const productInfo = ref<Partial<API.ProductVO>>({})

// 获取商品信息
const fetchProductInfo = async () => {
  try {
    const res = await getProductVoByIdUsingGet({ id: Number(productId) })
    productInfo.value = res.data
  } catch (error) {
    // 移除错误提示
  }
}

// 获取审核状态颜色
const getAuditStatusColor = (status: string | undefined) => {
  if (!status) return 'default'
  const colors = {
    [AUDIT_STATUS.PENDING]: 'warning',
    [AUDIT_STATUS.APPROVED]: 'success', 
    [AUDIT_STATUS.REJECTED]: 'error'
  }
  return colors[status] || 'default'
}

// 获取审核状态文本
const getAuditStatusText = (status: string | undefined) => {
  if (!status) return '-'
  return AUDIT_STATUS_TEXT[status] || '-'
}

// 表格列定义
const columns = [
  {
    title: '规格图片',
    dataIndex: 'image',
    key: 'image',
    width: 100
  },
  {
    title: '规格名称',
    dataIndex: 'quantity',
    key: 'quantity'
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price'
  },
  {
    title: '销量',
    dataIndex: 'sales',
    key: 'sales',
    width: 100,
    sorter: true
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '审核状态',
    dataIndex: 'auditStatus',
    key: 'auditStatus'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 250
  }
]

// 表格数据
const skuList = ref([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 获取规格列表
const fetchSkuList = async () => {
  loading.value = true
  try {
    const res = await listProductSkuvoByPageUsingPost({
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      productId: Number(productId)
    })
    skuList.value = res.data?.records || []
    pagination.value.total = res.data?.total || 0
  } catch (error) {
    // 错误处理由拦截器统一处理
  } finally {
    loading.value = false
  }
}

// 表格变化
const handleTableChange = (pag: {current: number, pageSize: number}) => {
  pagination.value = {
    ...pagination.value,
    current: pag.current,
    pageSize: pag.pageSize
  }
  fetchSkuList()
}

// 规格表单
const modalVisible = ref(false)
const modalTitle = ref('')
const skuForm = ref<API.ProductSKUAddRequest | API.ProductSKUUpdateRequest>({
  productId: Number(productId),
  quantity: '',
  price: 0,
  stock: 0,
  image: '',
  description: '',
  auditStatus: AUDIT_STATUS.PENDING // 新增时默认为待审核
})

// 审核表单
const auditModalVisible = ref(false)
const currentSku = ref<any>(null)
const auditForm = ref({
  id: 0,
  auditStatus: AUDIT_STATUS.APPROVED
})

// 新增规格
const handleAdd = () => {
  modalTitle.value = '新增规格'
  skuForm.value = {
    productId: Number(productId),
    quantity: '',
    price: 0,
    stock: 0,
    image: '',
    description: '',
    auditStatus: AUDIT_STATUS.PENDING // 新增时默认为待审核
  }
  modalVisible.value = true
}

// 编辑规格
const handleEdit = (record: any) => {
  modalTitle.value = '编辑规格'
  skuForm.value = { ...record }
  modalVisible.value = true
}

// 打开审核弹窗
const handleAudit = (record: any) => {
  currentSku.value = record
  auditForm.value = {
    id: record.id,
    auditStatus: AUDIT_STATUS.APPROVED // 默认选择通过
  }
  auditModalVisible.value = true
}

// 提交审核
const handleAuditSubmit = async () => {
  try {
    await updateProductSkuUsingPost({
      ...currentSku.value,
      auditStatus: auditForm.value.auditStatus
    })
    message.success('审核操作成功')
    auditModalVisible.value = false
    fetchSkuList()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 保存规格
const handleModalOk = async () => {
  try {
    const api = skuForm.value.id ? updateProductSkuUsingPost : addProductSkuUsingPost
    // 如果是农户编辑商品，设置为待审核状态
    if (userStore.userInfo?.userRole === USER_ROLE.FARMER) {
      skuForm.value.auditStatus = AUDIT_STATUS.PENDING
    }
    const res = await api(skuForm.value)
    message.success(`${modalTitle.value}成功`)
    modalVisible.value = false
    fetchSkuList()
  } catch (error) {
    // 移除错误提示
  }
}

// 删除规格
const handleDelete = async (record: any) => {
  try {
    const res = await deleteProductSkuUsingPost({
      id: record.id
    })
    message.success('删除成功')
    fetchSkuList()
  } catch (error) {
    // 移除错误提示
  }
}

// 切换规格状态
const handleToggleStatus = async (record: any) => {
  try {
    const res = await updateProductSkuUsingPost({
      id: record.id,
      productId: record.productId,
      quantity: record.quantity,
      price: record.price,
      stock: record.stock,
      image: record.image,
      description: record.description,
      status: record.status === PRODUCT_STATUS.ACTIVE ? PRODUCT_STATUS.INACTIVE : PRODUCT_STATUS.ACTIVE,
      auditStatus: record.auditStatus
    })
    message.success('操作成功')
    fetchSkuList()
  } catch (error) {
    // 移除错误提示
  }
}

onMounted(() => {
  fetchProductInfo()
  fetchSkuList()
})
</script>

<style scoped>
.sku-container {
  padding: 24px;
}
</style>
